package com.innovation.chengzhangriji.ui;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAddRequestBody;
import com.innovation.chengzhangriji.http.BabyAddResponse;
import com.innovation.chengzhangriji.http.BabyResponse;
import com.innovation.chengzhangriji.http.Change;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.CuteTwoImageView;
import com.innovation.chengzhangriji.ui.widget.SelectDateLayout;
import com.innovation.chengzhangriji.ui.widget.SelectRoleLayout;
import com.innovation.chengzhangriji.util.FileUtils;
import com.innovation.library.http.HeadInfo;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class NewDiaryDetailActivity extends BaseLoginActivity implements CuteToolbar.OnClickCuteToolbarListener {
    private RelativeLayout relativeLayout_sex, relativeLayout_readyday, relativeLayout_birstday, relativeLayout_gaosi, relativeLayout_name, relativeLayout_relationship;
    private FrameLayout frameLayout_sex, frameLayout_readyday, frameLayout_birstday, framelayout_gray;
    private RelativeLayout linearLayout_yimatima;
    private CuteTextView editText_readyday, editText_birstday, editText_yima_time, editText_relationship, tv_state,editText_petname, editText_sex;
    private HeadInfo mHeadInfo;
    private RoundedImageView roundedImageView;
    private int mState,sex_state;
    private BabyAddRequestBody mBabyBody;
    private Bitmap bp;
    private DatePickerDialog datePickerDialog;
    private BabyResponse mBaby;
    private String yy, dd, date,chengwei="",sex="",xuexing;
    private long time_yima, time_ready, time_bir;
    private Calendar calendar;
    private RoundedImageView mImageHead;
    private CharSequence temp;
    private ImageView iv_for_sex;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String imageUrl = null;
            switch (requestCode) {
                case Config.REQUEST_OPEN_CAMERA:
                    imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                    break;
                case Config.REQUEST_OPEN_PHOTO:
                    imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                    break;
                //性别
                case 3:
                    sex = data.getStringExtra("sex");
                    editText_sex.setText(data.getStringExtra("sex"));
//                    if (data.getStringExtra("sex").toString().trim().contains("男")) {
//                        iv_for_sex.setVisibility(View.VISIBLE);
//                        iv_for_sex.setImageResource(R.mipmap.icon_nan);
//                    } else if (data.getStringExtra("sex").toString().trim().contains("女")) {
//                        iv_for_sex.setVisibility(View.VISIBLE);
//                        iv_for_sex.setImageResource(R.mipmap.icon_nv);
//                    } else {
//                        iv_for_sex.setVisibility(View.INVISIBLE);
//                    }

                    break;
                //关系
                case 4:
                    chengwei = data.getStringExtra("relationship");
                    editText_relationship.setText(data.getStringExtra("relationship"));
                    break;
                case 5:

                    editText_petname.setText(data.getStringExtra("name"));
                    break;
            }
            if (!TextUtils.isEmpty(imageUrl)) {
                File imgFile = new File(imageUrl);
                if (imgFile.exists()) {
                    mHeadInfo.setHasHead(true);
                    mHeadInfo.setHeadExtension(FileUtils.getFileExtension(imageUrl));
                    mHeadInfo.setHeadBase64(FileUtils.encodeFileToBase64Binary(imgFile));
                    ImageLoader.getInstance().displayImage("file://" + imageUrl, roundedImageView);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_diary_detail);
        mHeadInfo = new HeadInfo();
        mBabyBody = new BabyAddRequestBody();
        mBaby = new BabyResponse();
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.new_diary_detail_cutetoolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        init();
    }

    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    @Override
    protected void onResume() {
        super.onResume();
//diary_detail_bg
    }

    protected void setbitmap(Bitmap bitmap) {
        Drawable drawable = new BitmapDrawable(convertToBlur(bitmap));
        relativeLayout_gaosi.setBackgroundDrawable(drawable);
    }

    private void init() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        date = df.format(new Date());
        calendar = Calendar.getInstance();
        iv_for_sex = (ImageView) findViewById(R.id.iv_for_sex);
        tv_state = (CuteTextView) findViewById(R.id.tv_state);
        framelayout_gray = (FrameLayout) findViewById(R.id.framelayout_gray);
        framelayout_gray.getBackground().setAlpha(178);
        editText_birstday = (CuteTextView) findViewById(R.id.edit_type3_baby_birstday);
        editText_readyday = (CuteTextView) findViewById(R.id.edit_type2_baby_readyday);
        editText_yima_time = (CuteTextView) findViewById(R.id.edit_text_yima_time);
        editText_petname = (CuteTextView) findViewById(R.id.edit_text_pet_name);
        editText_sex = (CuteTextView) findViewById(R.id.edit_text_sex);

        editText_relationship = (CuteTextView) findViewById(R.id.edit_text_relationship);
        relativeLayout_name = (RelativeLayout) findViewById(R.id.relativeLayout_text_name);
        relativeLayout_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewDiaryDetailActivity.this, BabyDetailChangeActivity.class);
                intent.putExtra("type", "name");
                intent.putExtra("from", 1);
                intent.putExtra("name", editText_petname.getText().toString());
                startActivityForResult(intent, 5);
            }
        });
        relativeLayout_relationship = (RelativeLayout) findViewById(R.id.relativeLayout_text_relationship);
        relativeLayout_relationship.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewDiaryDetailActivity.this, PetnameListActivity.class);
                intent.putExtra("type", "relationship");
                intent.putExtra("relationship", editText_relationship.getText().toString());
                startActivityForResult(intent, 4);
            }
        });
        roundedImageView = (RoundedImageView) findViewById(R.id.image_head);
        roundedImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDialog();
            }
        });
        relativeLayout_gaosi = (RelativeLayout) findViewById(R.id.diary_detail_bg);
        linearLayout_yimatima = (RelativeLayout) findViewById(R.id.yima_time);
        linearLayout_yimatima.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog = new DatePickerDialog(NewDiaryDetailActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                        if (i2 < 9) {
                            yy = "0" + (i2 + 1);
                        } else {
                            yy = "" + (i2 + 1);
                        }
                        if (i3 < 10) {
                            dd = "0" + i3;
                        } else {
                            dd = "" + i3;
                        }
                        date = i + "-" + yy + "-" + dd;
                        editText_yima_time.setText(i + "-" + yy + "-" + dd);
                        calendar.set(i, i2, i3, 0, 0, 0);
                        time_yima = calendar.getTimeInMillis();
                    }
                }, Integer.parseInt(date.substring(0, 4)), (Integer.parseInt(date.substring(5, 7)) - 1), Integer.parseInt(date.substring(8, 10)));
                datePickerDialog.show();
            }
        });
        relativeLayout_sex = (RelativeLayout) findViewById(R.id.type23_baby_sex);
        relativeLayout_sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewDiaryDetailActivity.this, PetnameListActivity.class);
                intent.putExtra("type", "sex");
                intent.putExtra("sex", editText_sex.getText().toString());
                intent.putExtra("state", mState);
                startActivityForResult(intent, 3);
            }
        });
        relativeLayout_readyday = (RelativeLayout) findViewById(R.id.type2_baby_readyday);
        relativeLayout_readyday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog = new DatePickerDialog(NewDiaryDetailActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                        if (i2 < 9) {
                            yy = "0" + (i2 + 1);
                        } else {
                            yy = "" + (i2 + 1);
                        }
                        if (i3 < 10) {
                            dd = "0" + i3;
                        } else {
                            dd = "" + i3;
                        }
                        date = i + "-" + yy + "-" + dd;
                        editText_readyday.setText(i + "-" + yy + "-" + dd);
                        calendar.set(i, i2, i3, 0, 0, 0);
                        time_ready = calendar.getTimeInMillis();
                    }
                }, Integer.parseInt(date.substring(0, 4)), (Integer.parseInt(date.substring(5, 7)) - 1), Integer.parseInt(date.substring(8, 10)));
                datePickerDialog.show();
            }
        });
        relativeLayout_birstday = (RelativeLayout) findViewById(R.id.type3_baby_birstday);
        relativeLayout_birstday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog = new DatePickerDialog(NewDiaryDetailActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                        if (i2 < 9) {
                            yy = "0" + (i2 + 1);
                        } else {
                            yy = "" + (i2 + 1);
                        }
                        if (i3 < 10) {
                            dd = "0" + i3;
                        } else {
                            dd = "" + i3;
                        }
                        date = i + "-" + yy + "-" + dd;
                        editText_birstday.setText(i + "-" + yy + "-" + dd);
                        calendar.set(i, i2, i3, 0, 0, 0);
                        time_bir = calendar.getTimeInMillis();
                    }
                }, Integer.parseInt(date.substring(0, 4)), (Integer.parseInt(date.substring(5, 7)) - 1), Integer.parseInt(date.substring(8, 10)));
                datePickerDialog.show();
            }
        });
        frameLayout_sex = (FrameLayout) findViewById(R.id.type23_baby_sex_line);
        frameLayout_readyday = (FrameLayout) findViewById(R.id.type2_baby_readyday_line);


        Intent intent = getIntent();
        mState = intent.getIntExtra("type", -1);
        if (mState == 0) {
//            bp = BitmapFactory.decodeResource(getResources(), R.mipmap.newbiary_ready);
            relativeLayout_gaosi.setBackgroundResource(R.mipmap.beiyun_mohu);
            relativeLayout_sex.setVisibility(View.GONE);
            relativeLayout_readyday.setVisibility(View.GONE);
            relativeLayout_birstday.setVisibility(View.GONE);
            frameLayout_sex.setVisibility(View.GONE);
            frameLayout_readyday.setVisibility(View.GONE);
            linearLayout_yimatima.setVisibility(View.VISIBLE);
            editText_yima_time.setText(date);
            tv_state.setText("备孕期");
        } else if (mState == 1) {
            relativeLayout_gaosi.setBackgroundResource(R.mipmap.huaiyun2_mohu);
//            bp = BitmapFactory.decodeResource(getResources(), R.mipmap.newbiary_pregnant);
            relativeLayout_sex.setVisibility(View.VISIBLE);
            relativeLayout_readyday.setVisibility(View.VISIBLE);
            relativeLayout_birstday.setVisibility(View.GONE);
            frameLayout_sex.setVisibility(View.VISIBLE);
            frameLayout_readyday.setVisibility(View.GONE);
            linearLayout_yimatima.setVisibility(View.GONE);
            editText_readyday.setText(date);
            editText_sex.setText("未知");
            tv_state.setText("怀孕中");
        } else if (mState == 2) {
//            bp = BitmapFactory.decodeResource(getResources(), R.mipmap.newbiary_growup);
            relativeLayout_gaosi.setBackgroundResource(R.mipmap.chengzhang_mohu);
            relativeLayout_sex.setVisibility(View.VISIBLE);
            relativeLayout_readyday.setVisibility(View.GONE);
            relativeLayout_birstday.setVisibility(View.VISIBLE);
            frameLayout_sex.setVisibility(View.GONE);
            frameLayout_readyday.setVisibility(View.VISIBLE);
            linearLayout_yimatima.setVisibility(View.GONE);
            editText_birstday.setText(date);
            editText_sex.setText("男");
//            iv_for_sex.setVisibility(View.VISIBLE);
//            iv_for_sex.setImageResource(R.mipmap.icon_nan);
            tv_state.setText("成长期");
        }
//        Drawable drawable = new BitmapDrawable(convertToBlur(bp));
//        relativeLayout_gaosi.setBackgroundDrawable(drawable);

    }

    @Override
    public void onClickLeft() {
        onBackPressed();
    }

    @Override
    public void onClickRight() {
        addBaby();
    }

    private void openDialog() {
        final CharSequence[] items = {"拍照", "从手机相册选择"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加头像");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                    case 0:
                        startHeadCameraForResult();
                        break;
                    case 1:
                        startHeadSelectForResult();
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void addBaby() {

        // 判断是否有数据为空
        if (TextUtils.isEmpty(editText_petname.getText()) || TextUtils.isEmpty(editText_relationship.getText())) {
            tipShow("请填写完整的信息");
            return;
        }

        if (mHeadInfo.isHasHead()) {
            babyHeadUpload();
        } else {
            babyUpload();
        }
    }

    private void babyHeadUpload() {
        LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        Client.requestPictureResourceUpload(this, phone, token, mHeadInfo.getHeadExtension(), mHeadInfo.getHeadBase64(), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                dismissProgressDialog();
                mHeadInfo.setHeadServerUrl(get(value.toString(), String.class));
                babyUpload();
            }

            @Override
            public void onChZhRJFailure(String value) {
                tipShow(value);
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                tipShow(value);
                dismissProgressDialog();
                finish();
            }
        }, networkUnavailableSampleImpl());
    }

    private void babyUpload() {
        final LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return;
        }
        final String parentID = login.getUserID();
        final String phone = login.getPhone();
        final String token = login.getToken().getAccessToken();
        setBabyAddRequestBody();
        Client.requestBabyAdd(this, phone, token, getChanges(), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                BabyAddResponse response = get(value.toString(), BabyAddResponse.class);
                if (response != null) {
                    int id = response.getId();
                    login.setBabyID(id);
                    setLoginInfo(login);

                    // 重新请求所有宝贝信息
                    getAllBabyInfo(login);
                    Log.e("asdasd", "1");
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
                finish();
            }
        }, networkUnavailableSampleImpl());
    }

    private void getAllBabyInfo(final LoginInfo loginInfo) {
        final String id = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        Client.requestAllBaby(this, phone, token, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.d("获取所有宝贝信息成功" + value.toString());
                AllBabyResponse response = get(value.toString(), AllBabyResponse.class);
                // 修改为直接进入Timeline
                if (response != null) {
                    setLoginInfo(loginInfo);
                    int length = response.getData().length;
                    int[] childIDArray = new int[length];
                    Auth[] auth = new Auth[length];
                    for (int i = 0; i < length; i++) {
                        childIDArray[i] = response.getData()[i].getId();
                        auth[i] = response.getData()[i].getAuth();
                    }
                    insertOrReplaceInTxBabyAndParent(id, auth, childIDArray);
                    insertOrReplaceInTxBaby(response.getData());
                    Config.startGetAllParentInfoService(NewDiaryDetailActivity.this);
                    // startTimelineActivity();
                    Intent intent = new Intent(NewDiaryDetailActivity.this, HomeActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent);
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

        }, networkUnavailableSampleImpl());
    }


    private void setBabyAddRequestBody() {
        String name = editText_petname.getText().toString().trim();
        String memberName = editText_relationship.getText().toString().trim();
        mBabyBody.setName(name);
        mBabyBody.setParentName(memberName);
        mBaby.setName(name);
        mBaby.setParentName(memberName);
        switch (editText_sex.getText().toString().trim()){
            case "男":
                sex_state = 1;
                break;
            case "女":
                sex_state = 2;
                break;
            default:
                sex_state = -1;
                break;
        }
        switch (mState) {
            case Config.EXTRA_OPEN_CREATE_STATE_READY:
                mBabyBody.setState(Client.STATE_READY);
                if (time_yima != 0) {
                    mBabyBody.setLastDate(time_yima);
                    mBabyBody.setBirthday(Client.EMPTY_TIME);
                    mBabyBody.setDueDate(Client.EMPTY_TIME);
                }else{
                    mBabyBody.setLastDate(calendar.getTimeInMillis());
                    mBabyBody.setBirthday(Client.EMPTY_TIME);
                    mBabyBody.setDueDate(Client.EMPTY_TIME);
                }
                mBabyBody.setGender(sex_state);
                mBaby.setGender(sex_state);
                mBaby.setState(Client.STATE_READY);
                mBaby.setLastDate(time_yima);
                break;
            case Config.EXTRA_OPEN_CREATE_STATE_START:
                mBabyBody.setState(Client.STATE_START);
                mBabyBody.setDueDate(time_ready);

                if (time_ready != 0) {
                    mBabyBody.setLastDate(Client.EMPTY_TIME);
                    mBabyBody.setDueDate(time_ready);
                    mBabyBody.setBirthday(Client.EMPTY_TIME);
                }else{
                    mBabyBody.setLastDate(Client.EMPTY_TIME);
                    mBabyBody.setDueDate(calendar.getTimeInMillis());
                    mBabyBody.setBirthday(Client.EMPTY_TIME);
                }
                mBabyBody.setGender(sex_state);
                mBaby.setGender(sex_state);
                mBaby.setState(Client.STATE_START);
                mBaby.setDueDate(time_ready);
                break;
            case Config.EXTRA_OPEN_CREATE_STATE_END:
                mBabyBody.setState(Client.STATE_END);
                mBabyBody.setBirthday(time_bir);
                if (time_bir != 0) {
                    mBabyBody.setDueDate(Client.EMPTY_TIME);
                    mBabyBody.setLastDate(Client.EMPTY_TIME);
                    mBabyBody.setBirthday(time_bir);
                }else{
                    mBabyBody.setLastDate(Client.EMPTY_TIME);
                    mBabyBody.setDueDate(Client.EMPTY_TIME);
                    mBabyBody.setBirthday(calendar.getTimeInMillis());
                }
                mBabyBody.setGender(sex_state);
                mBaby.setGender(sex_state);
                mBaby.setState(Client.STATE_END);
                mBaby.setBirthday(time_bir);
                break;
        }
        if (mHeadInfo.isHasHead()) {
            mBabyBody.setImageUrl(mHeadInfo.getHeadServerUrl());
            mBaby.setImageUrl(mHeadInfo.getHeadServerUrl());
        }
    }

    private Change[] getChanges() {
        return mBabyBody.getBabyAddRequestBody();
    }

    private void startHeadCameraForResult() {
        Intent intent = new Intent(NewDiaryDetailActivity.this, HeadCameraActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_CAMERA);
    }

    private void startHeadSelectForResult() {
        Intent intent = new Intent(NewDiaryDetailActivity.this, HeadPhotoActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_PHOTO);
    }

    private class HeadInfo {

        private boolean hasHead;

        private String headBase64;

        private String headExtension;

        private String headServerUrl;

        public boolean isHasHead() {
            return hasHead;
        }

        public void setHasHead(boolean hasHead) {
            this.hasHead = hasHead;
        }

        public String getHeadBase64() {
            return headBase64;
        }

        public void setHeadBase64(String headBase64) {
            this.headBase64 = headBase64;
        }

        public String getHeadExtension() {
            return headExtension;
        }

        public void setHeadExtension(String headExtension) {
            this.headExtension = headExtension;
        }

        public String getHeadServerUrl() {
            return headServerUrl;
        }

        public void setHeadServerUrl(String headServerUrl) {
            this.headServerUrl = headServerUrl;
        }
    }

    /**
     * 高斯模糊
     *
     * @param bmp
     * @return
     */
    public static Bitmap convertToBlur(Bitmap bmp) {
        // 高斯矩阵
        int[] gauss = new int[]{1, 2, 1, 2, 4, 2, 1, 2, 1};

        int width = bmp.getWidth();
        int height = bmp.getHeight();
        Bitmap newBmp = Bitmap.createBitmap(width, height,
                Bitmap.Config.RGB_565);

        int pixR = 0;
        int pixG = 0;
        int pixB = 0;

        int pixColor = 0;

        int newR = 0;
        int newG = 0;
        int newB = 0;

        int delta = 16; // 值越小图片会越亮，越大则越暗

        int idx = 0;
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        for (int i = 1, length = height - 1; i < length; i++) {
            for (int k = 1, len = width - 1; k < len; k++) {
                idx = 0;
                for (int m = -1; m <= 1; m++) {
                    for (int n = -1; n <= 1; n++) {
                        pixColor = pixels[(i + m) * width + k + n];
                        pixR = Color.red(pixColor);
                        pixG = Color.green(pixColor);
                        pixB = Color.blue(pixColor);

                        newR = newR + pixR * gauss[idx];
                        newG = newG + pixG * gauss[idx];
                        newB = newB + pixB * gauss[idx];
                        idx++;
                    }
                }

                newR /= delta;
                newG /= delta;
                newB /= delta;

                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                pixels[i * width + k] = Color.argb(255, newR, newG, newB);

                newR = 0;
                newG = 0;
                newB = 0;
            }
        }

        newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

        return newBmp;
    }

}
